<template>
  <div class="container">
    <span v-auth="{tag: '2'}" class="table-button">
      <el-button type="primary" :icon="CirclePlus" @click="handleAdd">
        新增
      </el-button>
    </span>
    <el-dialog :close-on-click-modal="false"
               :close-on-press-escape="false"
               :show-close="false"
               v-model="dialogFormVisible"
               :title="dialogTitle"
               width="700">
      <el-form status-icon :model="form" ref="formRef" label-width="auto" :rules="rules" style="max-width: 400px">
        <el-form-item label="父菜单" prop="fatherNumber">
          <!--<el-cascader clearable v-model="form.fatherNumber" :options="tableData" :props="props"/>-->
          <el-select
              filterable
              v-model="form.fatherNumber"
              @change="fatherNumberChange"
              placeholder="选择父菜单">
            <el-option
                :key="-1"
                label="根菜单"
                value="M"
            />
            <el-option
                v-for="item in tableData"
                :key="item.id"
                :label="item.menuName"
                :value="item.menuNumber"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单编号" prop="menuNumber">
          <el-input readonly placeholder="选择父菜单后自动填充" v-model.trim="form.menuNumber"
                    autocomplete="off"/>
        </el-form-item>
        <el-form-item label="菜单名称" prop="menuName">
          <el-input clearable placeholder="输入菜单名称" v-model.trim="form.menuName" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="路由路径" prop="pagePath">
          <el-input clearable placeholder="输入路由路径" v-model.trim="form.pagePath" autocomplete="off"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel(formRef)">取消</el-button>
          <el-button type="primary" @click="dialogConfirm(formRef)">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
    <div class="table-body">
      <el-table row-key="id" :data="tableData" style="width: 100%" :row-style="{ height: '50px' }"
                :tree-props="{ children: 'subMenuList' }">
        <template #empty>
          <el-empty description="暂无数据"/>
        </template>
        <el-table-column prop="fatherNumber" label="父菜单编号" width="auto"/>
        <el-table-column prop="menuNumber" label="菜单编号" width="auto"/>
        <el-table-column prop="menuName" label="菜单名称" width="auto"/>
        <el-table-column prop="pagePath" label="路由路径" width="auto"/>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <el-button v-auth="{tag: '2'}" v-if="scope.row.fatherNumber === 'M'" type="primary" :icon="CirclePlus"
                       @click="handleItemAdd(scope.row)"/>
            <el-button v-auth="{tag: '4'}" type="success" :icon="Edit" @click="handleEdit(scope.$index, scope.row)"/>
            <el-button v-auth="{tag: '8'}" type="danger" :icon="Delete" @click="handleDelete(scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          layout="prev, pager, next"
          :total="total"
      />
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import MenuRequest from '@/api/sys/MenuApi.js';
import {ElMessage, ElMessageBox} from "element-plus";
import {CirclePlus, Delete, Edit} from '@element-plus/icons-vue';

let form = ref({
  id: '',
  menuNumber: '',
  fatherNumber: '',
  menuName: '',
  pagePath: ''
});
let menuId = ref(0);
let pageSize = ref(10);
let currentPage = ref(1);
let total = ref(0);
let addType = ref(1);

let formRef = ref();
let dialogFormVisible = ref(false);
let dialogTitle = ref('新增');
let tableData = ref([]);
let props = {
  expandTrigger: 'hover',
  value: 'menuNumber',
  label: 'menuName',
  children: 'subMenuList'
};

onMounted(() => {
  menuId.value = history.state.m;
  getMenuList();
});

const getMenuList = () => {
  MenuRequest.queryMenuList({
    menuId: menuId.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  }).then(res => {
    tableData.value = res.data;
    total.value = res.total;
  });
}

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getMenuList();
}

const fatherNumberChange = (val) => {
  if (val === 'M') {
    form.value.menuNumber = val.concat((tableData.value.length + 1).toString().padStart(2, '0'));
  } else {
    let menu = tableData.value.find(item => item.menuNumber === val);
    let newMenuNumber = (menu.subMenuList.length + 1).toString().padStart(2, '0');
    form.value.menuNumber = menu.menuNumber + newMenuNumber;
  }
}

const handleAdd = () => {
  addType.value = 0;
  form.value = {};
  dialogTitle.value = '新增';
  dialogFormVisible.value = true;
}

const handleItemAdd = (row) => {
  addType.value = 1;
  form.value = {};
  let newMenuNumber = parseInt(row.subMenuList.length + 1).toString().padStart(2, '0');
  form.value.fatherNumber = row.menuNumber;
  form.value.menuNumber = row.menuNumber + newMenuNumber;
  dialogTitle.value = '新增';
  dialogFormVisible.value = true;
}

const handleEdit = (index, row) => {
  form.value = {...row};
  dialogTitle.value = '编辑';
  dialogFormVisible.value = true;
}

const dialogCancel = (formRef) => {
  dialogFormVisible.value = false;
  formRef.resetFields();
}

const handleDelete = (row) => {
  ElMessageBox.confirm('此操作将永久删除该菜单, 是否继续?', '删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    MenuRequest.deleteMenu(row.id, menuId.value).then(() => {
      ElMessage({
        type: 'success',
        message: '操作成功',
      });
      getMenuList();
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消',
    })
  });
}

const dialogConfirm = (formRef) => {
  formRef.validate(val => {
    if (val) {
      MenuRequest.editMenu({
        menuId: menuId.value,
        ...form.value
      }).then(() => {
        ElMessage({
          type: 'success',
          message: '操作成功',
        });
        getMenuList();
        formRef.resetFields();
        dialogFormVisible.value = false;
      });
    }
  });
}

const rules = {
  menuName: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === void 0 || value === '') {
          callback(new Error('请输入菜单名称'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  fatherNumber: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === void 0 || value === '') {
          callback(new Error('请输入父菜单编号'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  menuNumber: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === void 0 || value === '') {
          callback(new Error('请输入菜单编号'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ],
  pagePath: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === void 0 || value === '') {
          callback(new Error('请输入路由路径'));
        } else {
          callback();
        }
      }, trigger: 'blur'
    }
  ]
}

</script>
